package com.demo.java.runa;

import java.util.Map;

public class TestWaitingAndBlock implements Runnable{

    Map<String,Thread> threadMap;
    public TestWaitingAndBlock(Map<String,Thread> threadMap){
        this.threadMap = threadMap;
    }

    @Override
    public void run() {
        testWaiting(threadMap);
    }

    public synchronized static void testWaiting(Map<String,Thread> threadMap) {
        try {
            boolean hasWaited = false;
            boolean hasNotified = false;
            long startSec = System.currentTimeMillis()/1000;
            while(true){
                long passSec = System.currentTimeMillis()/1000-startSec;
                if(passSec>=4){
                    String otherName = Thread.currentThread().getName().equals("C")?"D":"C";
                    Thread otherThread = threadMap.get(otherName);

                    if("BLOCKED".equals(otherThread.getState().name())&&!hasWaited){
                        hasWaited = true;
                        TestWaitingAndBlock.class.wait();
                    }
                    if(!hasNotified){
                        hasNotified = true;
                        TestWaitingAndBlock.class.notify();
                    }
                }
                if(hasWaited){
                    if(passSec>=12){
                        break;
                    }
                }else{
                    if(passSec>=8){
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
